package com.cgtong.android.activity;

import android.app.Dialog;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cgtong.android.App;
import com.cgtong.android.R;
import com.cgtong.android.adapter.RecycleListAdapter;
import com.cgtong.android.base.BaseTitleActivity;
import com.cgtong.android.bean.ProblemBean;
import com.cgtong.android.mvp.contract.RecycleListContract;
import com.cgtong.android.mvp.presenter.RecycleListPresenter;
import com.cgtong.android.util.PostUtil;
import com.cgtong.android.widget.BaseDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.ApiResult;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 回收站
 * by zhuqingchun
 */
public class RecycleListActivity extends BaseTitleActivity implements RecycleListContract.View {

    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.swipe_layout)
    SwipeRefreshLayout mSwipeLayout;

    @BindView(R.id.search_txt)
    TextView mSearchTxt;
    @BindView(R.id.search_edt)
    EditText mSearchEdt;
    @BindView(R.id.clear_img)
    ImageView mClearImg;
    @BindView(R.id.search_fl)
    FrameLayout mSearchFl;
    @BindView(R.id.recycler_bottom_view)
    RelativeLayout mBottomLayout;
    @BindView(R.id.recovery_txt)
    TextView mRecovery;
    @BindView(R.id.delete_txt)
    TextView mDelete;

    private List<ProblemBean> mList;
    private RecycleListAdapter mAdapter;

    private RecycleListContract.Presenter mPresenter;
    private long mCurrUserId;
    private String mSearchKey = "";

    private SparseArray<ProblemBean> mRecycleArray;

    @Override
    protected String getContentTitle() {
        return getString(R.string.title_recycle_list);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_recycle_list;
    }

    @Override
    protected void loadDataByNet() {

        mTitleRightTxt.setVisibility(View.VISIBLE);
        mTitleRightTxt.setText(getString(R.string.txt_edit));
        mTitleRightTxt.setEnabled(false);
        mCurrUserId = App.getInstance().getCurrentAccount().getUserId();
        mPresenter = new RecycleListPresenter(this);
        mList = new ArrayList<>();
        mRecycleArray = new SparseArray<>();
        initRecyclerView();

        //回车键搜索监听
        mSearchEdt.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        mSearchEdt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    mSearchKey = mSearchEdt.getText().toString();
                    mPresenter.httpRecycleList(0, mSearchKey, mCurrUserId, true);
                    KeyboardUtils.hideSoftInput(mSearchEdt);
//                    mSearchEdt.setText("");
                    return false;
                }
                return false;
            }
        });
        //显示或隐藏清空按钮
        mSearchEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 0) {
                    mClearImg.setVisibility(View.GONE);
                    mSearchKey = "";
//                    loadDataByNet();
                } else {
                    mClearImg.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void initRecyclerView() {
        mSwipeLayout.setColorSchemeResources(R.color.color_scheme);
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mAdapter.setShowSelectBtn(false);
                mRecycleArray.clear();
                mTitleRightTxt.setText(getString(R.string.txt_edit));
                mPresenter.httpRecycleList(0, mSearchKey, mCurrUserId, true);
            }
        });
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new RecycleListAdapter(this, mList, mRecycleArray);
        mRecyclerView.setAdapter(mAdapter);
//        mRecyclerView.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.HORIZONTAL, R.drawable.shape_horizontal_divider));
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                long id = mAdapter.getItem(mAdapter.getItemCount() - 2).getId();
                mPresenter.httpRecycleList(id, mSearchKey, mCurrUserId, false);

            }
        }, mRecyclerView);
        mAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
//        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                if (!mAdapter.isShowSelectBtn()) {
//                ProblemBean problemBean = mAdapter.getItem(position);
//                ProblemDetailActivity.start(RecycleListActivity.this, mAdapter.getItem(position).getId(), false, false);
//                }
//            }
//        });
        mPresenter.httpRecycleList(0, mSearchKey, mCurrUserId, true);

    }

    @Override
    protected void onDataReloadByNet(View v) {
        mSearchKey = "";
        mPresenter.httpRecycleList(0, mSearchKey, mCurrUserId, true);
    }

    @Override
    public void setRefreshing(boolean isRefresh) {
        if (mSwipeLayout != null) {
            mSwipeLayout.setRefreshing(isRefresh);
        }
    }

    @Override
    public void setEnableLoadMore(boolean enableLoadMore) {
        mAdapter.setEnableLoadMore(enableLoadMore);

    }

    @Override
    public void onLoadMoreEnd(boolean isLoadMoreEnd) {
        mAdapter.loadMoreEnd(isLoadMoreEnd);
    }

    @Override
    public void onError(ApiException e) {
        PostUtil.postSuccessDelayed(loadService);
        mAdapter.setNewData(null);
        mAdapter.setEmptyView(R.layout.layout_error);
        mTitleRightTxt.setEnabled(false);

    }

    @Override
    public void onNullData() {
        PostUtil.postSuccessDelayed(loadService);
        mAdapter.setNewData(null);
        mAdapter.setEmptyView(R.layout.layout_empty);
        mTitleRightTxt.setEnabled(false);

    }

    @OnClick({R.id.clear_img, R.id.search_bar_fl, R.id.title_right_txt, R.id.delete_txt, R.id.recovery_txt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.clear_img:
                mSearchKey = "";
                mSearchEdt.setText("");
                KeyboardUtils.hideSoftInput(mSearchEdt);
                mPresenter.httpRecycleList(0, mSearchKey, mCurrUserId, true);
                break;
            case R.id.search_bar_fl:
                mSearchFl.setVisibility(View.VISIBLE);
                mSearchTxt.setVisibility(View.GONE);
                KeyboardUtils.showSoftInput(mSearchEdt);
                break;
            case R.id.title_right_txt:
                if (mAdapter.isShowSelectBtn()) {
                    LogUtils.d("集合大小：" + mRecycleArray.size());
                    mTitleRightTxt.setText(getString(R.string.txt_edit));
                    mBottomLayout.setVisibility(View.GONE);
                    mAdapter.toggleShowSelectBtn();
                    mAdapter.notifyDataSetChanged();
                } else {
                    mTitleRightTxt.setText(getString(R.string.title_left_cancel));
                    mBottomLayout.setVisibility(View.VISIBLE);
                    mAdapter.toggleShowSelectBtn();
                    mAdapter.notifyDataSetChanged();
                }
                break;
            case R.id.delete_txt:
                if (mAdapter.isShowSelectBtn()) {
                    LogUtils.d("集合大小：" + mRecycleArray.size());
                    int size = mRecycleArray.size();
                    StringBuffer sb = new StringBuffer();

                    for (int i = 0; i < size; i++) {
                        ProblemBean bean = mRecycleArray.valueAt(i);
                        sb.append(bean.getId()).append(",");
                        LogUtils.d(bean.toString());
                    }

                    if (sb.length() > 0) {
                        String ids = sb.substring(0, sb.length() - 1);
                        LogUtils.d("ids= " + ids);
//                        doShowLoading(this,true);
//                        mPresenter.commitRecycleProblemIDs(ids);
                        showDeleteDialog(ids);
                        // TODO: 2018/5/17 删除弹框
                    } else {
                        ToastUtils.showLong(getString(R.string.txt_delete_tip1));
                    }
                }
                break;
            case R.id.recovery_txt:
                if (mAdapter.isShowSelectBtn()) {
                    LogUtils.d("集合大小：" + mRecycleArray.size());
                    int size = mRecycleArray.size();
                    StringBuffer sb = new StringBuffer();

                    for (int i = 0; i < size; i++) {
                        ProblemBean bean = mRecycleArray.valueAt(i);
                        sb.append(bean.getId()).append(",");
                        LogUtils.d(bean.toString());
                    }

                    if (sb.length() > 0) {
                        String ids = sb.substring(0, sb.length() - 1);
                        LogUtils.d("ids= " + ids);
                        doShowLoading(this, true);
                        mPresenter.commitRecycleProblemIDs(ids);
                    } else {
                        ToastUtils.showLong(getString(R.string.txt_recycle_tip));
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onHttpRecycleListSuccess(List<ProblemBean> datas, boolean isRefresh) {
        PostUtil.postSuccessDelayed(loadService);
        mTitleRightTxt.setEnabled(true);
        if (isRefresh) {
            mAdapter.setNewData(datas);
//            mAdapter.disableLoadMoreIfNotFullPage(mRecyclerView);
        } else {
            mAdapter.addData(datas);
        }
        mAdapter.loadMoreComplete();
    }

    private void showDeleteDialog(final String ids) {
        BaseDialog.create(getSupportFragmentManager())
                .setLayoutRes(R.layout.layout_delete_record)
                .setViewListener(new BaseDialog.ViewListener() {

                    @Override
                    public void bindView(View view, final Dialog dialog) {
                        TextView okTxt = (TextView) view.findViewById(R.id.not_save_record_txt);
                        okTxt.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                doShowLoading(RecycleListActivity.this, true);
                                mPresenter.deleteRecycles(ids);
                                dialog.cancel();
                            }
                        });
                        TextView noTxt = (TextView) view.findViewById(R.id.cancel_txt);
                        noTxt.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.cancel();
                            }
                        });


                    }
                }).setDimAmount(0.3f)
                .setCanCancelable(false).
                setGravity(Gravity.BOTTOM)
                .show();
    }

    @Override
    public void onCommitRecycleProblemIDsSuccess(ApiResult result) {
        doHideLoading();
        if (result.getCode() == 0) {
            finish();
        }
        ToastUtils.showLong(result.getMsg());
    }

    @Override
    public void onDeleteRecycleIDsSuccess(ApiResult result) {
        doHideLoading();
        if (result.getCode() == 0 ){
            if (mRecycleArray != null) {
                int size = mRecycleArray.size();
                for (int i = 0; i < size; i++) {
                    ProblemBean bean = mRecycleArray.valueAt(i);
                    mAdapter.getData().remove(bean);
                }
                LogUtils.d("集合大小：" + mRecycleArray.size());
                mTitleRightTxt.setText(getString(R.string.txt_edit));
                mBottomLayout.setVisibility(View.GONE);
                mAdapter.toggleShowSelectBtn();
                mAdapter.notifyDataSetChanged();
            }
            return;
        }
        ToastUtils.showLong(result.getMsg());
    }
}
